package com.css.devops.service.jenkins;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.css.devops.service.DevopsCustom;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import com.offbytwo.jenkins.client.util.EncodingUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 自定义服务，补充 jenkins java client 没有封装的内容
 */
@Slf4j
@Service("jenkinsCustomService")
public class JenkinsCustomService implements DevopsCustom {

    /**
     * Jenkins http 客户端对象
     */
	@Autowired
    private JenkinsHttpClient jenkinsHttpClient;


    /**
     * 创建 Jenkins Job 并指定 Job 类型
     */
    @Override
	public void createJob(String jobName) {
        try {
            // 创建 Job 的xml
            String jobXml = "<project>\n" +
                                "<keepDependencies>false</keepDependencies>\n" +
                                "<properties/>\n" +
                                "<scm class=\"hudson.scm.NullSCM\"/>\n" +
                                "<canRoam>false</canRoam>\n" +
                                "<disabled>false</disabled>\n" +
                                "<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>\n" +
                                "<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>\n" +
                                "<triggers/>\n" +
                                "<concurrentBuild>false</concurrentBuild>\n" +
                                "<builders/>\n" +
                                "<publishers/>\n" +
                                "<buildWrappers/>\n" +
                                "<link type=\"text/css\" id=\"dark-mode\" rel=\"stylesheet\" href=\"\"/>\n" +
                            "</project>";
            // 创建 Jenkins Job 并指定 Job 类型
            jenkinsHttpClient.post_xml("createItem?name=" + EncodingUtils.encodeParam(jobName) + "&mode=hudson.model.FreeStyleProject", jobXml, true);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

}
